import "dart:async";
import "dart:convert";
import "dart:io";

import "package:ct_pa_majordomo/config/roomIcons.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/add_apartment/index.dart";
import "package:ct_pa_majordomo/pages/apartment/add_floor/index.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/room_operation/index.dart";
import "package:ct_pa_majordomo/pages/main.dart";
import "package:ct_pa_majordomo/pages/widgets/page_view_switcher.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:ct_pa_majordomo/widgets/wrap_item.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:provider/provider.dart";

import "../check_in_detail/api.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";

class Apartments extends StatefulWidget {
  final Map? params;
  const Apartments({super.key, this.params});

  @override
  ApartmentsState createState() => ApartmentsState();
}

class ApartmentsState extends State<Apartments> {
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  bool _isLoaded = false;
  int _total = 0;
  final List<FilterHeaderItem> _headerItems = [
    FilterHeaderItem(title: "公寓"),
    FilterHeaderItem(title: "状态"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];
  final Map _filter = {"pageNum": 1};
  List _apartments = [];
  List _apartmentFloors = [];
  List _status = [];
  int? _apartmentId;

  Future<void> _initialize() async {
    try {
      List resData = await Future.wait([
        apartmentApi.getApartments(),
        apartmentApi.getStatus(),
      ]);
      setState(() {
        _apartments = resData.first..insert(0, {"name": "全部"});
        _status = resData.last;
      });
    } catch (error) {
      print(error);
    }
  }

  Future<void> _getApartmentRooms() async {
    try {
      _isLoading = true;
      EasyLoading.show(status: "加载中...");
      Map<String, dynamic> params = {..._filter, "pageSize": 40, "type": 1};
      Map resData = await apartmentApi.getApartmentRooms(params);
      List data = resData["rows"] ?? [];
      setState(() {
        _headerItems.last.title = "数量：${resData["total"] ?? 0}";
        for (int aIndex = 0; aIndex < data.length; aIndex++) {
          Map apartment = data[aIndex];
          for (int fIndex = 0; fIndex < apartment["floorList"].length; fIndex++) {
            Map floor = apartment["floorList"][fIndex];
            Map value = {
              "buildingId": apartment["buildingId"],
              "buildingName": apartment["buildingName"],
              ...floor,
            };

            if (_filter["pageNum"] > 1 && aIndex == 0 && fIndex == 0) {
              Map lastFloor = _apartmentFloors[_apartmentFloors.length - 1];
              if (lastFloor != null && lastFloor["buildingName"] == apartment["buildingName"] && lastFloor["floorName"] == floor["floorName"]) {
                lastFloor = _apartmentFloors.removeLast();
                int length = floor["roomList"].length;
                _total += length;
                floor["roomList"].forEach((room) {
                  lastFloor["roomList"].add(room);
                });
                value["roomList"] = lastFloor["roomList"];
              }
            } else {
              int length = floor["roomList"].length;
              _total += length;
            }

            _apartmentFloors.add(value);
          }
        }
        print("_total:>>>$_total");
        if (_total >= resData["total"]) {
          _isLoaded = true;
        }
        _isLoading = false;
        EasyLoading.dismiss();
        // _apartmentFloors = data
        //     .map((apartment) {
        //       Iterable floorList = apartment["floorList"].map((floor) {
        //         floor["buildingId"] = apartment["buildingId"];
        //         floor["buildingName"] = apartment["buildingName"];
        //         floor["roomList"].forEach((room) => _total += 1);
        //         return floor;
        //       });
        //       return floorList;
        //     })
        //     .expand((ele) => ele)
        //     .toList();
      });
    } catch (error) {
      print(error);
      EasyLoading.dismiss();
    }
  }

  Future<void> _createBuilding(Map params) async {
    await apartmentApi.createBuilding(params);
    EasyLoading.showToast("添加成功");
    _refresh();
  }

  void _navigatorTo(String path) {
    Stacker.pushNamed(path);
  }

  Future<void> _removeFloor(Map params) async {
    await apartmentApi.removeFloor(params);
    EasyLoading.showToast("删除成功");
    Stacker.pop();
    _refresh();
  }

  void _showApartmentMenu() => showRoundedBottomSheet(
        builder: (context) => BottomSheetMenu(
          items: [
            BottomSheetMenuItem("添加整层", onTap: () {
              _navigatorTo(Keys.APARTMENT_FLOORS_ADD);
            }),
            // BottomSheetMenuItem("管理整栋")
          ],
        ),
      );

  void _changeApartment(item) => setState(() {
        _headerItems[0].title = item["name"] ?? "公寓";
        _filter["buildingId"] = item["buildingId"];
        _filter["pageNum"] = 1;
        if (item["floorList"] == null) {
          _filter.remove("floorIds");
        } else {
          _filter["floorIds"] =
              item["floorList"].map((ele) => ele["floorId"]).toList();
        }
        _refresh();
      });

  void _changeStatus(item) => setState(() {
    _headerItems[1].title = item["dictLabel"] ?? "全部房间";
    // 全部房间的状态为 "0",替换为空值
    _filter["status"] = item["dictValue"] == "0" ? "" : item["dictValue"];
    _filter["pageNum"] = 1;
    _refresh();
  });

  void _showFloorMenu({required Map floor}) => showRoundedBottomSheet(
        builder: (context) => BottomSheetMenu(
          items: [
            BottomSheetMenuItem("新增房间", onTap: () {
              _addRoomDialog(buildingName: floor["buildingName"], floor: floor["floorName"], buildingId: floor["buildingId"]);
            }),
            BottomSheetMenuItem("删除整层", onTap: () {
              Map params = { "buildingId": floor["buildingId"], "floorIds": floor["floorId"].toString(), "apartmentId": _apartmentId };
              _removeFloorDialog(params);
            }),
            // BottomSheetMenuItem("批量关联公区锁"),
          ],
        ),
      );

  void _addRoomDialog({
    required int buildingId,
    required String buildingName,
    required String floor,
  }) {
    String textValue = "";
    taiDialog(
      context: context,
      title: "新增房间",
      onConfirm: (taiContext) {
        setState(() async {
          Map params = {
            "buildingId": buildingId,
            "floors": [{
              "floor": floor,
              "roomNameList": [textValue],
            }]
          };
          await _createBuilding(params);
          // Navigator.of(taiContext).pop();
          Stacker.pop();
        });
      },
      contentPadding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
      child: Column(
        children: [
          Text("$buildingName $floor层"),
          const SizedBox(height: 5,),
          TextFormField(
            autofocus: true,
            textAlign: TextAlign.center,
            decoration: const InputDecoration(
              hintText: "请输入",
              hintStyle: TextStyle(color: ThemeVars.colorTextTer),
              border: InputBorder.none,
              filled: true,
              fillColor: ThemeVars.colorBackground,
            ),
            initialValue: textValue,
            onChanged: (val) {
              textValue = val;
            },
          ),
        ],
      )
    );
  }

  void _removeFloorDialog(Map params) {
    taiDialog(
      context: context,
      child: const Text("确认删除整层所有房间？", textAlign: TextAlign.center,),
      onConfirm: (taiContext) {
        _removeFloor(params);
      }
    );
  }

  Future<void> _getCheckInInfo(Map room, int? checkInId) async {
    if (checkInId != null) {
      Map resData = await checkInApi.getCheckInInfo(checkInId: checkInId);
      Map data = resData["data"];
      Map roomInfo = data["room"];
      roomInfo["roomDirtyStatus"] = room["roomDirtyStatus"];
      roomInfo = {...roomInfo, ...room};
      Map mainRenter = data["renterList"].firstWhere((renter) => renter["mainFlag"] == "1");
      if (context.mounted) {
        roomOperation(
          context: context,
          info: resData["data"],
          mainRenter: mainRenter,
          room: roomInfo,
          onRefresh: (refresh) {
            print("初始页:>>> $refresh");
            if (refresh) {
              _refresh();
            }
          }
        );
      }
    } else {
      if (context.mounted) {
        roomOperation(
          context: context,
          room: room,
          onRefresh: (refresh) {
            print("初始页:>>> $refresh");
            if (refresh) {
              _refresh();
            }
          }
        );
      }
    }

  }

  Widget _renderApartment(int index) {
    Map floor = _apartmentFloors[index];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                color: ThemeVars.colorMask,
              ),
              child: Text(
                "${floor["buildingName"]}栋 ${floor["floorName"]}层",
                style: const TextStyle(color: Colors.white),
              ),
            ),
            const SizedBox(width: 10),
            GestureDetector(
              onTap: () => _showFloorMenu(floor: floor),
              child: const Icon(
                Icons.settings_rounded,
                color: ThemeVars.colorPrimary,
              ),
            ),
          ],
        ),
        const SizedBox(height: 10),
        Wrap(
          runSpacing: 10,
          spacing: 10,
          children: floor["roomList"].map<Widget>((room) {
            return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                room["buildingName"] = floor["buildingName"];
                print("room:>>>>$room");
                // if (room["checkInInfo"]?["checkInId"] != null) {
                  _getCheckInInfo(room, room["checkInInfo"]?["checkInId"]);
                // }
                // _getCheckInInfo();
                // roomOperation(context, info);
              },
              child: Stack(
                children: [
                  WrapItem(
                    span: 4,
                    child: AspectRatio(
                      aspectRatio: 3 / 2,
                      child: Container(
                        padding: const EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: const [ThemeVars.boxShadow],
                          color: room["checkInInfo"]?["checkInId"] != null ? ThemeVars.colorPrimaryLight : Colors.white,
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              room["roomName"],
                              style: const TextStyle(fontWeight: FontWeight.w500),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                room["associatedLockList"].isEmpty ? SizedBox() : Icon(Icons.lock_open, size: 12, color: ThemeVars.colorPrimary,),
                                room["associatedMeterList"].isEmpty ? SizedBox() : Icon(Icons.electric_meter_outlined, size: 12, color: ThemeVars.colorPrimary,),
                                Expanded(
                                  child: room["checkInInfo"]?["checkInId"] != null
                                    ? Text(
                                      "${room["checkInInfo"]["betweenNowDays"]}/${room["checkInInfo"]["betweenDays"]}",
                                      style: TextStyle(fontSize: 11),
                                      textAlign: TextAlign.right,
                                    )
                                    : Text("空置", style: TextStyle(fontSize: 11, color: ThemeVars.colorWarning), textAlign: TextAlign.right,)
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                  if (room["roomDirtyStatus"] == "1") Positioned(
                    top: 4,
                    right: 4,
                    child: Container(
                      width: 20,
                      height: 20,
                      decoration: BoxDecoration(
                        // color: ThemeVars.colorPrimaryLight,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: const Icon(
                        RoomIcons.clean_room,
                        size: 14,
                        color: ThemeVars.colorError,
                      ),
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  Future<void> _refresh() async {
    setState(() {
      _total = 0;
      _filter["pageNum"] = 1;
      _isLoaded = false;
      _apartmentFloors = [];
    });
    Future.delayed(const Duration(seconds: 2));
    // _initialize();
    _getApartmentRooms();
  }

  void _onScroll() {
    if (_isLoading || _isLoaded) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _filter["pageNum"] += 1;
        _getApartmentRooms();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _initialize();
    if (Utils.isNotEmpty(widget.params?["status"])) {
      setState(() {
        _filter["status"] = widget.params?["status"];
        _headerItems[1].title = widget.params?["label"];
      });
    }
    _refresh();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // final Map? apartment = Provider.of<CommonState>(context).apartment;
    final Map? apartment = jsonDecode(storage.getString("apartment") ?? "");
    _apartmentId = apartment?["apartmentId"];
    
    return PageViewSwitcher(
      items: const ["整栋"],
      actions: [
        IconButton(
          onPressed: () => Stacker.pushNamed(Keys.APARTMENT_ADD),
          icon: const Icon(Icons.add_rounded, color: Colors.white),
        ),
        IconButton(
          onPressed: _showApartmentMenu,
          icon: const Icon(Icons.menu_rounded, color: Colors.white),
        ),
      ],
      children: [
        FilterLayout(
          headerItems: _headerItems,
          dropdownItems: [
            FilterDropdownItem(
              items: _apartments,
              compare: (item) => item["buildingId"] == _filter["buildingId"],
              itemAsString: (item) => item["name"],
              onChanged: _changeApartment,
            ),
            FilterDropdownItem(
              items: _status,
              compare: (item) => item["dictValue"] == _filter["status"],
              itemAsString: (item) => item["dictLabel"],
              onChanged: _changeStatus,
            ),
          ],
          child: RefreshIndicator(
            onRefresh: _refresh,
            child: _apartmentFloors.isEmpty && !_isLoading
              ? Column(
                children: [
                  EmptyData(text: "暂无房间",),
                  SizedBox(height: 16,),
                  if (Utils.isEmpty(_filter["status"])) Button(
                    child: Text("添加房间"),
                    onPressed: () => Stacker.pushNamed(Keys.APARTMENT_ADD),
                  ),
                ],
              )
              : ListView.separated(
                  controller: _scrollController,
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  itemCount: _apartmentFloors.length,
                  itemBuilder: (context, index) => _renderApartment(index),
                  separatorBuilder: (context, index) => const SizedBox(height: 15),
                ),
          ),
        ),
      ],
    );
  }

  // 添加刷新方法，供外部调用
  void refresh() {
    _refresh();
  }
}
